import $http from '@/common/api/request.js';
export default{
	state:{
		// 存储从数据库中获取到的 我的足迹列表数据
		list:[],
		// 将选择的
		selectedList:[]
	},
	getters:{
		// 判断是否全选
		goods_collect_checkedAll(state){
			return state.list.length === state.selectedList.length;
		}
	},
	mutations:{
		// 将获取到数据赋值给list
		initGetGoodsCollectData(state,list){
			state.list = list
		},
	
		// 全选
		goods_collect_checkAll(state){
			state.selectedList = state.list.map(v=>{
				v.checked = true
				return v.id
			})
		},
		// 全不选
		goods_collect_unCheckAll(state){
			state.list.forEach(v=>{
				v.checked = false
			})
			state.selectedList = []
		},
		// 单选
		goods_collect_selectedItem(state,index){
			// 获取列表对象shopId
			let id = state.list[index].shopId
			// 根据id拿到selectedList列表中该id的下标
			let i = state.selectedList.indexOf(id)
			//如果selectedList已经存在就代表他之前是选中状态, checked=false,并且在selectedList删除
			if(i > -1){
				state.list[index].checked = false
				return state.selectedList.splice(i,1)
			}
			// 如果之前没有选中，checked=true,把当前的id添加到selectedList中
			state.list[index].checked = true;
			state.selectedList.push(id)
		},
		// 删除
		goods_collect_delGoods(state){
			state.list = state.list.filter(v=>{
				// 返回对应id所在 selectedList 中的索引
				return state.selectedList.indexOf(v.shopId)
			})
		},
	},
	actions:{
		// 全选或全不选事件
		goods_collect_checkedAllFn({commit,getters}){
			
			getters.goods_collect_checkedAll  ?  commit("goods_collect_unCheckAll")  :  commit("goods_collect_checkAll");
		},
		// 删除事件
		goods_collect_delGoodsFn({commit,state}){
			uni.showModal({
				content:'确定删除吗?',
				success: () => {
					$http.request({
						url:"/deleteCollectGoods",
						method:"POST",
						header:{
							token:true
						},
						data:{
							goodsId:state.selectedList
						}
					}).then((res)=>{
						commit('goods_collect_delGoods');
						commit('goods_collect_unCheckAll');
						uni.showToast({
							title:'删除成功',
							icon:"none"
						})
						
					}).catch(()=>{
						uni.showToast({
							title:'请求失败',
							icon:'none'
						})
					})
				}
			})
			
		}
	}
}